package com.mrd.gtimp.business.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.gtimp.business.entity.TaxInform;
import com.mrd.gtimp.business.service.TaxInformBiz;
import com.mrd.gtimp.sup.service.SupComConfBiz;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class TaxInformAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private TaxInformBiz taxInformBiz;
    @Resource
    private SupComConfBiz supComConfBiz;
    @Resource
    private SystemValueBiz systemValueBiz;

    /**
     * 默认访问入口
     */
    @RequestMapping("/taxInform-main")
    public String main() {
        return "/gtimp/business/taxInformList";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/taxInform-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/taxInform-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(TaxInform taxInform) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(taxInform.getId())) { // 新增操作
                    // taxInform.setCOM_ID(user.getCompany().getId());
                    // taxInform.setCREATOR(user.getAccount());
                    // taxInform.setCTIME(new Date());
                    taxInform.setId(null);
                } else { // 修改操作
                    // taxInform.setMODIFIER(user.getAccount());
                    // taxInform.setMTIME(new Date());
                }
                taxInformBiz.saveOrupdateEntity(taxInform);
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/taxInform-find")
    public TaxInform find(TaxInform taxInform) {
        if (null != taxInform) {
            if (StringUtils.isNotEmpty(taxInform.getId())) {
                try {
                    taxInform = taxInformBiz.findEntityById(taxInform.getId());
                    return taxInform;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除信息
     */
    @RequestMapping("/taxInform-del")
    @ResponseBody
    public Result del(Filter filters) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                String ids = HttpUtils.getParam("id");
                String[] idArr = ids.split(",");
                StringBuffer sb = new StringBuffer();
                for (String string : idArr) {
                    sb.append("'").append(string).append("',");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    filters = new Filter();
                    filters.setGroupOp(FilterGroupOption.AND);
                    filters.addRule(new SearchRule("id", SearchRuleOption.in, sb.toString()));
                    taxInformBiz.deleteByFilter(filters);
                }
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 查询
     */
    @RequestMapping("/taxInform-findList")
    @ResponseBody
    public Page<TaxInform> findList(User user) {
        String comId = user.getCompany().getId();// get from user
        Filter filters = null;
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("COM_ID", SearchRuleOption.eq, comId);
            filters.addRule(rule);
//            page = initPage(taxInformBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
//            taxInforms = taxInformBiz.findByJqgrid(page.getCurrentPageStartNo(), page
//                    .getPageSize(), filters, order);
            Pageable page = new PageRequest(0, 15, Sort.Direction.DESC);
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<TaxInform> taxInforms = taxInformBiz.findByJqgrid(jqgrid);
            return taxInforms;
        } catch (QueryException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 供应商退税单管理列表
     */
    @RequestMapping("/taxInform-findListForSup")
    @ResponseBody
    public String findListForSup(User user, Filter filters) {
        try {
            String comId = user.getCompany().getId();// get from user
            int alertDays = supComConfBiz.findTaxRange(comId);// 供应商设置的退税提醒期限
            if (filters == null) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            //// TODO: 2016/8/15  order
//            Order order = new Order();
//            order.add("ctime", "desc");
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }

            String listCase = "select * from ";
            String whereCase = "(select distinct t.BUSINESS_ID as biz_id, c.COMPANY_NAME as cname, c.PHONE as cphone, t.CTIME as ctime from T_BIZ_BASE_BUSINESS t, T_BIZ_CONTACTER c where t.REAL_CUSTOMER_ID=c.ID  and 1=1 and t.sup_id = '"
                    + comId + "' ";
            whereCase += ")  mtb right join (select tt.*,SYSVAL.B_CHN_NAME from t_biz_tax_inform tt , T_SYS_BASE sysval where TT.STATE=SYSVAL.B_IDENTIFIER) ttt on mtb.biz_id=ttt.BIZ_ID where 1=1 ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and " + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and " + field + " not in ('" + data + "') ";
                    } else {
                        whereCase = whereCase + " and " + field + " like '%" + data + "%' ";
                    }
                }
            }

            String orderCase = " order by ";
            //// TODO: 2016/8/15  page
//            for (String key : order.keySet()) {
//                orderCase = orderCase + " " + key + " " + (order.get(key) ? "desc" : "asc") + ",";
//            }
//            if (!" order by ".equals(orderCase)) {
//                orderCase = orderCase.substring(0, orderCase.length() - 1);
//            } else {
//                orderCase = "";
//            }
//
//            String countCase = "select count(*) from ";
//            List<Object> countlist = taxInformBiz
//                    .findObjectBySql(countCase + whereCase, 1, 1, new HashMap<String, Object>());
//            page = initPage(((BigDecimal) countlist.get(0)).intValue());
//            List<Object> list = taxInformBiz.findObjectBySql(listCase + whereCase + orderCase, page
//                    .getCurrentPageStartNo(), page.getPageSize(), new HashMap<String, Object>());
//            taxInformDTOs = new ArrayList<TaxInformDTO>();
//            for (Object objects : list) {
//                Object[] objs = (Object[]) objects;
//                TaxInformDTO tempDto = new TaxInformDTO();
//                BusinessDto bDto = new BusinessDto();
//                bDto.setBusiId(objs[0] == null ? "" : objs[0].toString());
//                bDto.setCustomerName(objs[1] == null ? "" : objs[1].toString());
//                bDto.setCtime((Date) objs[3]);
//                tempDto.setBusinessDto(bDto);
//
//                TaxInform tt = new TaxInform();
//                tt.setId(objs[4] == null ? "" : objs[4].toString());
//                tt.setState(objs[7] == null ? "" : objs[7].toString());
//                tt.setReturnDate((Date) objs[6]);
//                tt.setSupRemark(objs[8] == null ? "" : objs[8].toString());
//                tt.setReleaseDate((Date) objs[9]);
//                tt.setTaxBpk(objs[10] == null ? "" : objs[10].toString());
//                tt.setAlertState(objs[13] == null ? "0" : objs[13].toString());
//                tempDto.setTaxInform(tt);
//                tempDto.setStateString(objs[14] == null ? "" : objs[14].toString());
//                if (null != tt.getReleaseDate()) {
//                    tempDto.setDeadLineDate(TaxDeadLineDateBuilder.getTaxDeadLineDate(tt
//                            .getReleaseDate()));
//                    if (null != tt.getState() && !BaseTypeConstant.TAX_STATE_3.equals(tt.getState())
//                            && !"1".equals(tt.getAlertState()) && !"2".equals(tt.getAlertState())
//                            && TaxDeadLineDateBuilder.isTaxAlert(tt.getReleaseDate(), alertDays)) {
//                        taxInformBiz.updateAlertTax(tt.getId());
//                        tt.setAlertState("1");
//                    }
//                }
//                taxInformDTOs.add(tempDto);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ///// TODO: 2016/8/15
//        return "gridDataForSup";
        return null;
    }

    /**
     * 标记为已结退
     */
    @RequestMapping("/taxInform-validateReturnTax")
    @ResponseBody
    public Result validateReturnTax(User user) {
        Result msg;
        try {
            String taxId = HttpUtils.getParam("id");
            taxInformBiz.updateReturnTax(taxId, user.getAccount());
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 标记为已退回
     */
    @RequestMapping("/taxInform-validateBackTax")
    @ResponseBody
    public Result validateBackTax(User user) {
        Result msg;
        try {
            String taxId = HttpUtils.getParam("id");
            TaxInform entity = taxInformBiz.findEntityById(taxId);
            if (entity != null && BaseTypeConstant.TAX_STATE_0.equals(entity.getState())) {
                taxInformBiz.updateBackTax(taxId, user.getAccount());
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 检查业务是否可以标记为已退回
     */
    @RequestMapping("/taxInform-validateCheckBackTax")
    @ResponseBody
    public Result validateCheckBackTax() {
        Result msg;
        try {
            String taxId = HttpUtils.getParam("id");
            TaxInform entity = taxInformBiz.findEntityById(taxId);
            if (entity != null && BaseTypeConstant.TAX_STATE_0.equals(entity.getState())) {
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @Resource
    public void setTaxInformBiz(TaxInformBiz taxInformBiz) {
        this.taxInformBiz = taxInformBiz;
    }

    public SupComConfBiz getSupComConfBiz() {
        return supComConfBiz;
    }

    @Resource
    public void setSupComConfBiz(SupComConfBiz supComConfBiz) {
        this.supComConfBiz = supComConfBiz;
    }

    public SystemValueBiz getSystemValueBiz() {
        return systemValueBiz;
    }

    @Resource
    public void setSystemValueBiz(SystemValueBiz systemValueBiz) {
        this.systemValueBiz = systemValueBiz;
    }
}
